package com.atlin.project.manager.factory;

import com.atlin.project.model.domain.LoginInfo;
import com.atlin.project.service.impl.LoginInfoServiceImpl;
import com.atlin.project.utils.*;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;

import java.util.Date;
import java.util.TimerTask;

/**
 * 异步工厂（产生异步任务用）
 *
 * @author atlin
 */
@Slf4j
public class AsyncFactory {

    /**
     * 记录登录信息
     *
     * @param userAccount 用户
     * @param status      状态
     * @param message     消息
     * @param args        列表
     * @return 任务task
     */
    public static TimerTask recordLoginInfo(final String userAccount, final String status,
                                            final String message, final Object... args) {
        final String ip = NetUtils.getIpAddress();
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        return new TimerTask() {
            @Override
            public void run() {
                // 计时
                StopWatch stopWatch = new StopWatch();
                stopWatch.start();
                String address = AddressUtils.getRealAddressByIP(ip);
                StringBuilder s = new StringBuilder();
                s.append(LogUtils.getBlock(ip));
                s.append(LogUtils.getBlock(address));
                s.append(LogUtils.getBlock(userAccount));
                s.append(LogUtils.getBlock(status));
                s.append(LogUtils.getBlock(message));

                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                //获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                //封装对象
                LoginInfo loginInfo = new LoginInfo();
                loginInfo.setUserAccount(userAccount);
                loginInfo.setIpaddr(ip);
                loginInfo.setLoginLocation(address);
                loginInfo.setBrowser(browser);
                loginInfo.setOs(os);
                loginInfo.setStatus(status);
                loginInfo.setMsg(message);
                loginInfo.setLoginTime(new Date());
                //插入数据
                SpringContextUtils.getBean(LoginInfoServiceImpl.class).save(loginInfo);
                stopWatch.stop();
                s.append(LogUtils.getBlock("cost", stopWatch.getTotalTimeMillis(), "ms"));
                // 打印信息到日志
                log.info(s.toString(), args);
            }
        };
    }

}
